package com.blue.base.web.bean;

import com.blue.base.common.exception.BaseException;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.web.context.request.WebRequest;

import java.util.Map;
import java.util.Objects;

/**
 * 重写异常信息获取逻辑
 *
 * @author liulei
 * @version 1.0
 */
public class DefineErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String, Object> attributes = super.getErrorAttributes(webRequest, includeStackTrace);
        Throwable throwable = this.getError(webRequest);
        if (Objects.isNull(throwable)) {
            return attributes;
        }
        // 如果不是常规MVC异常，则走filter异常处理策略
        if (throwable instanceof BaseException) {
            BaseException generalException = (BaseException) throwable;
            attributes.put("code", generalException.getCode());
            attributes.put("error", generalException.getMessage());
        }
        return attributes;
    }
}
